package com.ylr.send.framework.service.impl;

import com.ylr.send.common.dto.SmsTemplateFlowDto;
import com.ylr.send.common.vo.SmsTemplateFlowFormVo;
import com.ylr.send.framework.service.SmsTemplateFlowService;
import com.ylr.base.common.dto.PageDto;
import com.ylr.base.common.enums.CommonEnum;
import com.ylr.base.common.enums.ResultEnum;
import com.ylr.base.common.exception.YlrException;
import com.ylr.base.common.po.user.UserPo;
import com.ylr.base.common.utils.UserUtils;
import com.ylr.base.framework.service.SnowflakeService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ylr.send.framework.entity.SmsTemplateFlowEntity;
import com.ylr.send.framework.mapper.SmsTemplateFlowMapper;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-06-14 21:21:36
 * className: SmsTemplateFlowServiceImpl
 * version: 1.0
 * description:
 */
@Service("smsTemplateFlowService")
@AllArgsConstructor
public class SmsTemplateFlowServiceImpl extends ServiceImpl<SmsTemplateFlowMapper, SmsTemplateFlowEntity> implements SmsTemplateFlowService {

    private static final Logger log = LoggerFactory.getLogger(SmsTemplateFlowServiceImpl.class);

    private final SnowflakeService snowflakeService;

    @Override
    public void saveSmsTemplateFlow(Long smsTemplateId, Integer channel, String code, String tname, String content, String params, Integer version) {
        // 获取正在保存短信模板的用户
        UserPo userPo = UserUtils.getUser();

        SmsTemplateFlowEntity smsTemplateFlow = this.newSmsTemplateFlow(smsTemplateId, channel, code, tname, content, params, version, userPo);
        // 保存数据
        baseMapper.insert(smsTemplateFlow);
        log.info("保存短信模板流水完成");
    }

    @Override
    public PageDto<SmsTemplateFlowDto> pageSmsTemplateFlowList(SmsTemplateFlowFormVo smsTemplateFlowFormVo) {

        // mp分页对象
        Page<SmsTemplateFlowEntity> page = new Page<>(smsTemplateFlowFormVo.getPageNo(), smsTemplateFlowFormVo.getPageSize());

        LambdaQueryWrapper<SmsTemplateFlowEntity> smsTemplateFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询字段
        smsTemplateFlowLambdaQueryWrapper.select(SmsTemplateFlowEntity::getId, SmsTemplateFlowEntity::getChannel,
                SmsTemplateFlowEntity::getCode, SmsTemplateFlowEntity::getTname, SmsTemplateFlowEntity::getContent,
                SmsTemplateFlowEntity::getParams, SmsTemplateFlowEntity::getVersion, SmsTemplateFlowEntity::getCreateTime,
                SmsTemplateFlowEntity::getCreateUser);
        // 匹配条件
        smsTemplateFlowLambdaQueryWrapper.eq(SmsTemplateFlowEntity::getSmsTemplateId, smsTemplateFlowFormVo.getSmsTemplateId())
                .eq(SmsTemplateFlowEntity::getDeleteStatus, CommonEnum.DELETE_NO.getValue());
        // 排序
        smsTemplateFlowLambdaQueryWrapper.orderByDesc(SmsTemplateFlowEntity::getId);
        // 查询数据
        baseMapper.selectPage(page, smsTemplateFlowLambdaQueryWrapper);

        List<SmsTemplateFlowEntity> smsTemplateFlowList = page.getRecords();
        long totalNum = page.getTotal();
        if (smsTemplateFlowList.isEmpty()) {
            log.info("短信模板流水为空");
            return new PageDto<>(Collections.emptyList(), totalNum, smsTemplateFlowFormVo.getPageNo(), smsTemplateFlowFormVo.getPageSize());
        }

        // 数据构造
        List<SmsTemplateFlowDto> smsTemplateFlowDtoList = new ArrayList<>(smsTemplateFlowList.size());
        for (SmsTemplateFlowEntity smsTemplateFlow : smsTemplateFlowList) {
            smsTemplateFlowDtoList.add(this.getSmsTemplateFlowDto(smsTemplateFlow));
        }
        return new PageDto<>(smsTemplateFlowDtoList, totalNum, smsTemplateFlowFormVo.getPageNo(), smsTemplateFlowFormVo.getPageSize());
    }

    @Override
    public SmsTemplateFlowDto getSmsTemplateFlow(Long smsTemplateId, Integer version) {

        LambdaQueryWrapper<SmsTemplateFlowEntity> smsTemplateFlowLambdaQueryWrapper = new LambdaQueryWrapper<>();
        // 查询字段
        smsTemplateFlowLambdaQueryWrapper.select(SmsTemplateFlowEntity::getId, SmsTemplateFlowEntity::getChannel,
                SmsTemplateFlowEntity::getCode, SmsTemplateFlowEntity::getTname, SmsTemplateFlowEntity::getContent,
                SmsTemplateFlowEntity::getParams, SmsTemplateFlowEntity::getVersion, SmsTemplateFlowEntity::getCreateTime,
                SmsTemplateFlowEntity::getCreateUser);
        // 匹配条件
        smsTemplateFlowLambdaQueryWrapper.eq(SmsTemplateFlowEntity::getSmsTemplateId, smsTemplateId)
                .eq(Objects.nonNull(version), SmsTemplateFlowEntity::getVersion, version)
                .eq(SmsTemplateFlowEntity::getDeleteStatus, CommonEnum.DELETE_NO.getValue());
        // 排序
        smsTemplateFlowLambdaQueryWrapper.orderByDesc(SmsTemplateFlowEntity::getId);
        smsTemplateFlowLambdaQueryWrapper.last("LIMIT 1");
        // 查询数据
        List<SmsTemplateFlowEntity> smsTemplateFlowList = baseMapper.selectList(smsTemplateFlowLambdaQueryWrapper);
        if (smsTemplateFlowList.isEmpty()) {
            log.info("短信模板流水为空");
            throw new YlrException(ResultEnum.NOT_FOUND);
        }
        // 封装返回
        return this.getSmsTemplateFlowDto(smsTemplateFlowList.get(0));
    }

    @Override
    public void deleteSmsTemplateFlow(List<Long> idList) {
        LambdaUpdateWrapper<SmsTemplateFlowEntity> smsTemplateFlowLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        // 设置字段值
        smsTemplateFlowLambdaUpdateWrapper.set(SmsTemplateFlowEntity::getDeleteStatus, CommonEnum.DELETE_YES.getValue());
        // 匹配条件
        smsTemplateFlowLambdaUpdateWrapper.in(SmsTemplateFlowEntity::getId, idList)
                .eq(SmsTemplateFlowEntity::getDeleteStatus, CommonEnum.DELETE_NO.getValue());
        // 更新数据
        int count = baseMapper.update(null, smsTemplateFlowLambdaUpdateWrapper);
        log.info("删除短信模板完成。count={}", count);
    }

    /**
     * 生成短信模板流水对象
     * @param channel 短信渠道
     * @param code    编号
     * @param tname   名称
     * @param content 内容
     * @param params  模板预设字段，多个值使用英文逗号分割
     * @param version 版本号
     * @param userPo  操作用户
     * @return 短信模板流水对象
     */
    private SmsTemplateFlowEntity newSmsTemplateFlow(Long smsTemplateId, Integer channel, String code, String tname,
                                                     String content, String params, Integer version, UserPo userPo) {
        SmsTemplateFlowEntity smsTemplateFlow = new SmsTemplateFlowEntity();
        smsTemplateFlow.setId(snowflakeService.getId())
                .setSmsTemplateId(smsTemplateId)
                .setChannel(channel)
                .setCode(code)
                .setTname(tname)
                .setContent(content)
                .setParams(params)
                .setVersion(version)
                .setDeleteStatus(CommonEnum.DELETE_NO.getValue())
                .setCreateTime(new Date())
                .setCreateUser(userPo.getUsername())
                .setCreateUserId(userPo.getId());
        return smsTemplateFlow;
    }

    /**
     * 短信模板流水实体对象封装
     * @param smsTemplateFlow 短信模板流水实体对象
     * @return 封装结果
     */
    private SmsTemplateFlowDto getSmsTemplateFlowDto(SmsTemplateFlowEntity smsTemplateFlow) {
        SmsTemplateFlowDto smsTemplateFlowDto = new SmsTemplateFlowDto();
        smsTemplateFlowDto.setId(smsTemplateFlow.getId().toString())
                .setChannel(smsTemplateFlow.getChannel())
                .setCode(smsTemplateFlow.getCode())
                .setTname(smsTemplateFlow.getTname())
                .setContent(smsTemplateFlow.getContent())
                .setParams(smsTemplateFlow.getParams())
                .setVersion(smsTemplateFlow.getVersion())
                .setCreateTime(smsTemplateFlow.getCreateTime())
                .setCreateUser(smsTemplateFlow.getCreateUser());
        return smsTemplateFlowDto;
    }
}